package com.tabbar.demo.fragment;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.koushikdutta.async.future.Future;
import com.koushikdutta.async.http.WebSocket;
import com.tabbar.demo.R;
import com.tabbar.demo.service.ForegroundEnablingService;
import com.tabbar.demo.service.ForegroundService;
import com.tabbar.demo.util.ToolLog;

import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketException;
import de.tavendo.autobahn.WebSocketHandler;


/**
 * User:Shine
 * Date:2015-10-20
 * Description:
 */
public class HomeFragment extends PageFragment implements View.OnClickListener {
    private String TAG="websocket";
    private EditText mEdtText;
    private Future<WebSocket> websocket;
    private WebSocketConnection webSocketConnection;
    private TextView mTvMsg;
    private int count = 0;
    private String url = "ws://127.0.0.1:20016";
//    private okhttp3.WebSocket mWebsocket;

    public static PageFragment newInstance(int page) {
        Bundle args = new Bundle();
        args.putInt(ARGS_PAGE, page);
        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        Button button = (Button) view.findViewById(R.id.button);
        Button btWebSocket = (Button) view.findViewById(R.id.bt_open_websocket);
        Button btSendData = (Button) view.findViewById(R.id.bt_send);
        mEdtText = (EditText) view.findViewById(R.id.edt_text);
        mTvMsg = (TextView) view.findViewById(R.id.tv_message);
        button.setOnClickListener(this);
        btWebSocket.setOnClickListener(this);
        btSendData.setOnClickListener(this);
        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                int largeMemoryClass = ((ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE)).getLargeMemoryClass();
                showShort("当前内存：" + largeMemoryClass);
                Activity activity = getActivity();
                activity.startService(new Intent(activity, ForegroundService.class));
                activity.startService(new Intent(activity, ForegroundEnablingService.class));
                break;
            case R.id.bt_open_websocket:
                openWebsocket();
//                openWebsocket2();
                break;
            case R.id.bt_send:
                sendDataAuto();
//                sendRxMsg();
                break;
        }
    }

    private void sendDataAuto() {
        count++;
        if (webSocketConnection != null) {
            if (TextUtils.isEmpty(mEdtText.getText().toString())) {
                webSocketConnection.sendTextMessage("abcdefg+" + count);
            } else {
                webSocketConnection.sendTextMessage(mEdtText.getText().toString() + count);
            }
        } else {
            ToolLog.w("web", "websocketconnect is null");
        }
        return;
    }

    private void openWebsocket() {
        webSocketConnection = new WebSocketConnection();
        try {
            webSocketConnection.connect(url, new WebSocketHandler() {
                @Override
                public void onOpen() {
                    ToolLog.i(TAG, "onOpen: ");
                    webSocketConnection.sendTextMessage("abcd efghi");
                }

                @Override
                public void onTextMessage(String payload) {
                    ToolLog.i(TAG, "onTextMessage: " + payload);
                    mTvMsg.setText(payload);
                }

                @Override
                public void onClose(int code, String reason) {
                    ToolLog.i(TAG, "onClose: " + code + "|" + reason);
                }
            });
        } catch (WebSocketException e) {
            e.printStackTrace();
        }
    }


//    /**
//     * RXWebsockt https://github.com/dhhAndroid/RxWebSocket
//     */
//    private void openWebsocket2() {
//        OkHttpClient yourClient = new OkHttpClient();
//        RxWebSocketUtil.getInstance().setClient(yourClient);
//        // show ToolLog,default false
//        RxWebSocketUtil.getInstance().setShowLog(true);
//        //websocket
////        RxWebSocketUtil.getInstance().setSSLSocketFactory(yourSSlSocketFactory,yourX509TrustManager);
////        RxWebSocketUtil.getInstance().getWebSocket(url);
//
//        RxWebSocketUtil.getInstance().getWebSocketInfo(url)
//                //RxLifecycle : https://github.com/dhhAndroid/RxLifecycle
//                .compose(RxLifecycle.with(this).<WebSocketInfo>bindOnDestroy())
//                .subscribe(new WebSokcetAction1() {
//                    @Override
//                    public void onOpen(@NonNull okhttp3.WebSocket webSocket) {
//                        ToolLog.w(TAG, "open .success");
//                    }
//
//                    @Override
//                    public void onMessage(@NonNull String text) {
//                        ToolLog.w(TAG, "收到消息：" + text);
//                    }
//
//                    @Override
//                    public void onMessage(@NonNull ByteString bytes) {
//                        ToolLog.w(TAG, "收到消息：" + bytes.toString());
//                    }
//                });
//
//    }
//
//    private void sendRxMsg() {
//        count++;
//        if (mWebsocket != null) {
//            mWebsocket.send("当前第" + count + "次发送");
//        }
//    }
}
